import { getPublicKey, login } from '@/api/login'
import { authLoginUser, getAuthRandom, checkShow } from '@/api/authLogin'
import { getMenu } from '@/api/menu'
// import { login } from '@/api/login'
import { setSessionId, removeSessionId, setUserInfo, getUserInfo, removeUserInfo, removeOem, setAuthUserInfo, setAuthSessionId, removeAuthUserInfo, removeAuthSessionId, removeRoleList } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie'
import md5 from 'js-md5'
import CryptoJS from 'crypto-js'
// import JsEncrypt from 'jsencrypt'

const state = {
  sessionId: '',
  userInfo: '',
  role: '',
  isSetRoutes: false,
  roleList: [],
  passwordFlag: false,
  roleInfo: []
}

const mutations = {
  SET_SWSSIONID: (state, sessionId) => {
    state.sessionId = sessionId
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
    state.role = userInfo.role || ''
  },
  SET_ISSETROUTES: (state, isSetRoutes) => {
    state.isSetRoutes = isSetRoutes
  },
  SET_ROLE: (state, roleList) => {
    state.roleList = roleList[0]
    state.roleInfo = roleList[1]
  },
  SET_PASSWORDFLAG: (state, passwordFlag) => {
    state.passwordFlag = passwordFlag
  }
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      let keyForm = JSON.parse(JSON.stringify(userInfo))
      keyForm.username = username.trim()
      keyForm.password = ''
      getPublicKey(keyForm).then(res => {
        if (res.status === 0) {
          let key = actions.RSAKeyEncrypt(res.info[0].key, res.info[0].date, password)
          let formData = JSON.parse(JSON.stringify(userInfo))
          formData.username = username.trim()
          formData.password = key[0]
          formData['seed'] = key[1]
          formData['session_id'] = res.info[0].session_id
          login(formData).then(response => {
            // const { info } = response
            // commit('SET_SWSSIONID', info[0].session_id)
            // commit('SET_USERINFO', info[0])
            // setUserInfo(info[0])
            // setSessionId(info[0].session_id)
            commit('SET_PASSWORDFLAG', true)

            resolve(response)
          }).catch(error => {
            reject(error)
          })
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  loginAuth ({ commit }, userInfo) {
    const { name, password } = userInfo
    return new Promise((resolve, reject) => {
      getAuthRandom({ name: name.trim() }).then(res => {
        if (res.status === 0) {
          let key = actions.encrypt(password, res.info)
          let formData = JSON.parse(JSON.stringify(userInfo))
          formData.name = name.trim()
          formData.password = key
          authLoginUser(formData).then(response => {
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        }
      })
    })
  },
  // user logout
  logout ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.sessionId).then(() => {
      commit('SET_SWSSIONID', '')
      commit('SET_USERINFO', '')
      commit('SET_ROLE', ['', ''])
      commit('SET_PASSWORDFLAG', false)
      removeSessionId()
      removeUserInfo()
      removeOem()
      removeRoleList()
      commit('SET_ISSETROUTES', false)
      sessionStorage.removeItem('store')
      Cookies.remove('store')
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
      // if (this.$socket) {
      //   this.$socket.close()
      //   this.$socket.disconnect()
      // }
      // reset visited views and cached views
      // dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
  // user logout
  logoutAuth ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      removeAuthUserInfo()
      removeAuthSessionId()
      Cookies.remove('store')
      resolve()
    })
  },

  // 保存登录信息
  saveInfo ({ commit }, info) {
    return new Promise((resolve, reject) => {
      commit('SET_SWSSIONID', info.session_id)
      commit('SET_USERINFO', info)
      setUserInfo(info)
      setSessionId(info.session_id)
      resolve(info)
    })
  },
  saveInfoAuth ({ commit }, info) {
    return new Promise((resolve, reject) => {
      setAuthUserInfo(info)
      setAuthSessionId(info.session_id)
      resolve(info)
    })
  },
  savePassword ({ commit }, info) {
    return new Promise((resolve, reject) => {
      commit('SET_PASSWORDFLAG', false)
      resolve(info)
    })
  },
  // 配合登录权限设置，改变issetroutes
  issetroutesChange ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMenu({ roleID: getUserInfo().roleID }).then(response => {
        // const { info } = response
        // commit('SET_SWSSIONID', info[0].session_id)
        // commit('SET_USERINFO', info[0])
        // setUserInfo(info[0])
        // setSessionId(info[0].session_id)
        commit('SET_ISSETROUTES', true)
        commit('SET_USERINFO', getUserInfo())
        commit('SET_ROLE', [response.url_list, response.info])
        // const { role } = getUserInfo()
        // resolve(role)
        const path = response.url_list
        resolve(path)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove sessionId
  resetSessionId ({ commit }) {
    return new Promise(resolve => {
      commit('SET_SWSSIONID', '')
      setSessionId('')
      resolve()
    })
  },
  // 加密
  RSAKeyEncrypt (key, date, password) {
    let private_key = actions.getrandom()
    let password_new = md5(encodeURI(password + date))
    let secret_key = actions.encrypt(password_new, private_key)
    let seed = actions.RSAencrypt(private_key, key)
    return [secret_key, seed]
  },
  // 加密随机数
  getrandom () {
    const char = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    let key = ''
    for (let i = 0; i < 32; i++) {
      let index = Math.round(Math.random() * (char.length - 1))
      key += char[index]
    }
    return key
  },
  // AES ECB 加密
  encrypt (word, keyStr) {
    let key = CryptoJS.enc.Utf8.parse(keyStr)
    let srcs = CryptoJS.enc.Utf8.parse(word)
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
  },
  // seed RSA JSEncrpt加密
  RSAencrypt (password, public_key) {
    // 实例化jsEncrypt对象
    let jse = new JSEncrypt() // 在index.html中引用
    // 设置公钥
    jse.setPublicKey(public_key)
    return jse.encrypt(password)
  },
  authLoginShow ({ commit }) {
    const hrefUrl = window.location.href.match(/[0-9][-0-9]{0,62}(\.[0-9][-0-9]{0,62})+\.?/)
    const ipPattern = hrefUrl || window.location.href.match(/((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?/)
    return new Promise((resolve, reject) => {
      checkShow({ ip: ipPattern ? ipPattern[0] : '' }).then(res => {
        if (res.status === 0) {
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
